﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.QrCode.Internal;

namespace Protocal.App.Common
{
    public static class QRCodeHelper
    {
        /// <summary>
        /// 默认二维码尺寸
        /// </summary>
        private const int DEFAULT_SIZE = 300;

        /// <summary>
        /// 默认字符编码
        /// </summary>
        private static readonly Encoding DEFAULT_ENCODING = Encoding.UTF8;

        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="content">要编码的内容</param>
        /// <param name="size">图片尺寸（正方形）</param>
        /// <param name="margin">边距</param>
        /// <param name="errorCorrectionLevel">纠错级别</param>
        /// <returns>生成的二维码位图</returns>
        public static Bitmap GenerateQRCode(string content, ErrorCorrectionLevel errorCorrectionLevel,int size = DEFAULT_SIZE,int margin = 2)
        {
            if (string.IsNullOrWhiteSpace(content))
            {
                throw new ArgumentException("内容不能为空", nameof(content));
            }

            var options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                CharacterSet = "UTF-8",
                Width = size,
                Height = size,
                Margin = margin,
                ErrorCorrection = errorCorrectionLevel
            };

            var writer = new BarcodeWriter<Bitmap>()
            {
                Format = BarcodeFormat.QR_CODE,
                Options = options
            };

            return writer.Write(content);
        }

        /// <summary>
        /// 生成二维码并保存到文件
        /// </summary>
        /// <param name="content">要编码的内容</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="size">图片尺寸</param>
        /// <param name="margin">边距</param>
        /// <param name="errorCorrectionLevel">纠错级别</param>
        public static void GenerateAndSaveQRCode(string content,string filePath, ErrorCorrectionLevel errorCorrectionLevel,int size = DEFAULT_SIZE,int margin = 2)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("文件路径不能为空", nameof(filePath));
            }

            using (var bitmap = GenerateQRCode(content, errorCorrectionLevel,size, margin))
            {
                bitmap.Save(filePath, GetImageFormat(filePath));
            }
        }

        public static byte[] BitmapToBytes(Bitmap bitmap, ImageFormat format)
        {
            if (bitmap == null)
                throw new ArgumentNullException(nameof(bitmap));

            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, format); // 指定格式（如 ImageFormat.Png）
                return ms.ToArray();
            }
        }

        /// <summary>
        /// 从二维码图片中解析内容
        /// </summary>
        /// <param name="bitmap">包含二维码的位图</param>
        /// <returns>解析出的字符串内容</returns>
        public static string DecodeQRCode(Bitmap bitmap, ImageFormat format)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            var reader = new BarcodeReader()
            {
                AutoRotate = true,
                TryInverted = true,
                Options = new DecodingOptions
                {
                    PossibleFormats = new[] { BarcodeFormat.QR_CODE },
                    CharacterSet = "UTF-8"
                }
            };

            // 不同类型的图片转换为Bitmap的方法  
            //Image image = Image.FromFile("xx");
            //var bitmap = new Bitmap(image);

            byte[] bitArray;
            using(var stream = new MemoryStream())
            {
                bitmap.Save(stream, format);
                bitArray = stream.ToArray();
            }
            var result = reader.Decode(bitArray);
            return result?.Text;
        }

        /// <summary>
        /// 从文件中的二维码图片解析内容
        /// </summary>
        /// <param name="filePath">二维码图片文件路径</param>
        /// <returns>解析出的字符串内容</returns>
        public static string DecodeQRCodeFromFile(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("文件路径不能为空", nameof(filePath));
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("指定的文件不存在", filePath);
            }

            using (var bitmap = new Bitmap(filePath))
            {
                ImageFormat format = GetImageFormat(filePath);
                return DecodeQRCode(bitmap, format);
            }
        }

        /// <summary>
        /// 根据文件扩展名获取图像格式
        /// </summary>
        private static ImageFormat GetImageFormat(string filePath)
        {
            var extension = Path.GetExtension(filePath)?.ToLower();
            switch (extension)
            {
                case ".png":
                    return ImageFormat.Png;
                case ".jpg":
                case ".jpeg":
                    return ImageFormat.Jpeg;
                case ".bmp":
                    return ImageFormat.Bmp;
                case ".gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Png; // 默认PNG格式
            }
        }
    }
}
